//
//  KWNSetViewController.m
//  KWNClient
//
//  Created by 张明磊 on 14-5-10.
//  Copyright (c) 2014年 张明磊. All rights reserved.
//

#import "KWLSetViewController.h"
#import "RESideMenu.h"
#import "KWLAoutusViewController.h"
#import "KWNNetwork.h"
#import "Model_user.h"
#import "KWLLoginViewController.h"
#import "KWLFindMMViewController.h"
#import "MLBlackTransition.h"
#import "MINavigationController.h"
#import <StoreKit/StoreKit.h>

@interface KWLSetViewController ()<UITableViewDelegate,UITableViewDataSource,SKStoreProductViewControllerDelegate>
@property BOOL ifCheckVersion;
@property (nonatomic,strong) UITableView *tableView_home;

@end

@implementation KWLSetViewController
@synthesize ifCheckVersion;
@synthesize tableView_home;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){

    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"CheckVersion"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    NSString *string_ifCheckVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"CheckVersion"];
    if (!string_ifCheckVersion || [string_ifCheckVersion isEqualToString:@"0"]) {
        ifCheckVersion = NO;
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"CheckVersion"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else
    {
        ifCheckVersion = YES;
    }

    [self UI_set];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UITableView *tab = (UITableView *)[self.view viewWithTag:TagOfView];
    if (tab) {
        [tab reloadData];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
    if(ifCheckVersion == NO)
    {
        // 后台执行：
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // something
            NSString *newVersion;
            NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/cn/lookup?id=944922678"];
            //通过url获取数据
            NSData *data_json = [NSData dataWithContentsOfURL:url];
            NSError *error;
            if (data_json != nil)
            {
                NSDictionary *kindDic = [NSJSONSerialization JSONObjectWithData:data_json options:NSJSONReadingMutableLeaves error:&error];
                
                if (!error)
                {
                    //从数据字典中检出版本号数据
                    NSArray *configData = [kindDic valueForKey:@"results"];
                    for(id config in configData){
                        newVersion = [config valueForKey:@"version"];
                    }
                    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
                    
                    if ([newVersion floatValue] < [localVersion floatValue])
                    {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            self.ifCheckVersion = NO;
                            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"CheckVersion"];
                            [[NSUserDefaults standardUserDefaults] synchronize];
                            [self.tableView_home reloadData];
                        });
                    }
                    else{
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            self.ifCheckVersion = YES;
                            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"CheckVersion"];
                            [[NSUserDefaults standardUserDefaults] synchronize];
                            [self.tableView_home reloadData];
                        });
                    }
                }
            }
        });
    }
}

- (void)dealloc
{
    UITableView *tab = (UITableView *)[self.view viewWithTag:TagOfView];
    if (tab) {
        tab = nil;
    }
}

- (void)UI_set{
    self.view.backgroundColor = RGB(239, 239, 244);
    
    UIView *imageView_title = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44 + IOS7_SIZE)];
    imageView_title.backgroundColor = RGB(91, 165, 229);
    [self.view addSubview:imageView_title];
    
    UIButton *button_menu = [UIButton buttonWithType:UIButtonTypeCustom];
    button_menu.frame = CGRectMake(0, IOS7_SIZE, 60, 45);
    [button_menu setImage:[UIImage imageFileName:@"btn_leftList.png"] forState:UIControlStateNormal];
    button_menu.tag = 0;
    [button_menu addTarget:self action:@selector(click_set:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button_menu];
    //button_menu.tag = KWNRegistButtonTag_back;
    
    UILabel *label_title = [[UILabel alloc] initWithFrame:CGRectMake(imageView_title.frame.origin.x,IOS7_SIZE + 5,imageView_title.frame.size.width,35)];
    label_title.backgroundColor = [UIColor clearColor];
    label_title.textColor = ColorOfTitle;
    label_title.textAlignment = NSTextAlignmentCenter;
    label_title.font = [UIFont fontWithName:@"Helvetica-Bold" size:16.0f];
    [self.view addSubview:label_title];
    label_title.text = @"系统设置";
    
    tableView_home = [[UITableView alloc] initWithFrame:CGRectMake(imageView_title.frame.origin.x, imageView_title.frame.origin.y + imageView_title.frame.size.height, imageView_title.frame.size.width, self.view.frame.size.height - imageView_title.frame.size.height )];
    tableView_home.backgroundColor = [UIColor clearColor];
    tableView_home.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView_home.delegate = self;
    tableView_home.dataSource = self;
    tableView_home.tag = TagOfView;
    [self.view addSubview:tableView_home];
}

- (void)click_set:(UIButton *)button{
    switch (button.tag){
        case 0:{
            [[RESideMenu sharedInstance] presentMenuViewController];
            [MobClick event:@"caidan"];
        }break;
        case 1:{
            
        }break;
        default:
            break;
    }
}

/**
 *  列表数据源
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell_Set";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle: 	UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    UIButton *btn_one = (UIButton *)[cell viewWithTag:100];
    UIButton *btn_xiugai = (UIButton *)[cell viewWithTag:101];
    UIButton *btn_two = (UIButton *)[cell viewWithTag:102];
    UIButton *btn_three = (UIButton *)[cell viewWithTag:103];
    UIButton *btn_quit = (UIButton *)[cell viewWithTag:105];
    if (btn_one) {
        [btn_one removeFromSuperview];
        btn_one = nil;
    }
    if (btn_xiugai) {
        [btn_xiugai removeFromSuperview];
        btn_xiugai = nil;
    }
    if (btn_two) {
        [btn_two removeFromSuperview];
        btn_two = nil;
    }
    if (btn_three) {
        [btn_three removeFromSuperview];
        btn_three = nil;
    }
    if (btn_quit) {
        [btn_quit removeFromSuperview];
        btn_quit = nil;
    }
    UIButton *button_xiugai = [UIButton buttonWithType:UIButtonTypeCustom];
    button_xiugai.frame = CGRectMake(0, 20, 320, 44);
    button_xiugai.backgroundColor = [UIColor clearColor];
    [button_xiugai setImage:[UIImage imageFileName:@"set_xiugaimima.png"] forState:UIControlStateNormal];
    [button_xiugai setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button_xiugai addTarget:self action:@selector(didClickButton_xiugai:)forControlEvents:UIControlEventTouchUpInside];
    button_xiugai.tag = 101;
    [cell addSubview:button_xiugai];
    
    UIButton *button_one = [UIButton buttonWithType:UIButtonTypeCustom];
    button_one.frame = CGRectMake(0, button_xiugai.frame.origin.y + button_xiugai.frame.size.height + 20, 320, 44);
    [button_one setImage:[UIImage imageFileName:@"set_0.png"] forState:UIControlStateNormal];
    [button_one addTarget:self action:@selector(didClickButton_set:)forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:button_one];
    button_one.tag = 100;
    
    if (ifCheckVersion == NO)
    {
        
        UIButton *button_quit = [UIButton buttonWithType:UIButtonTypeCustom];
        button_quit.frame = CGRectMake(10, button_one.frame.origin.y + button_one.frame.size.height + 70, 300, 46);
        button_quit.backgroundColor = RGB(239, 99, 101);
        [button_quit setTitle:@"退出登录" forState:UIControlStateNormal];
        [button_quit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button_quit addTarget:self action:@selector(didClickButton_set:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:button_quit];
        button_quit.layer.cornerRadius = 5.0;
        button_quit.tag = 105;
        button_quit.hidden = YES;
        
    }
    else
    {
        UIButton *button_two = [UIButton buttonWithType:UIButtonTypeCustom];
        button_two.frame = CGRectMake(button_one.frame.origin.x, button_one.frame.origin.y + button_one.frame.size.height, 320, 44);
        [button_two setImage:[UIImage imageFileName:@"set_1.png"] forState:UIControlStateNormal];
        [button_two addTarget:self action:@selector(app_checkVersion)forControlEvents:UIControlEventTouchUpInside];
        button_two.tag = 102;
        [cell addSubview:button_two];
        
        UIButton *button_three = [UIButton buttonWithType:UIButtonTypeCustom];
        button_three.frame = CGRectMake(button_two.frame.origin.x, button_two.frame.origin.y + button_two.frame.size.height , 320, 44);
        button_three.backgroundColor = [UIColor clearColor];
        [button_three setImage:[UIImage imageFileName:@"set_2.png"] forState:UIControlStateNormal];
        [button_three addTarget:self action:@selector(app_evaluate)forControlEvents:UIControlEventTouchUpInside];
        button_three.tag = 103;
        [cell addSubview:button_three];
        
        UIButton *button_quit = [UIButton buttonWithType:UIButtonTypeCustom];
        button_quit.frame = CGRectMake(10, button_three.frame.origin.y + button_three.frame.size.height + 70, 300, 46);
        button_quit.backgroundColor = RGB(239, 99, 101);
        [button_quit setTitle:@"退出登录" forState:UIControlStateNormal];
        [button_quit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button_quit addTarget:self action:@selector(didClickButton_set:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:button_quit];
        button_quit.layer.cornerRadius = 5.0;
        button_quit.tag = 105;
        button_quit.hidden = YES;
    }

    
    UIButton *button_quit_ = (UIButton *)[cell viewWithTag:105];
    NSString *string_token = [[Model_user sharedInstance] getToken];
    if(string_token){
        button_quit_.hidden = NO;
    }
    else
    {
        button_quit_.hidden = YES;
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return tableView.frame.size.height;
}

- (void)didClickButton_set:(UIButton *)button{
    switch (button.tag) {
        case 100:{
            KWLAoutusViewController *about = [[KWLAoutusViewController alloc] init];
            [self pushViewController:about];
        }break;
        case 105:{
            [SVProgressHUD showWithStatus:@"退出中..." maskType:SVProgressHUDMaskTypeClear];
            [[KWNNetwork sharedInstance] login_outfinishBlock:^(NSInteger stateCode, NSMutableArray *result) {
                switch (stateCode) {
                    case 10000:{
                        button.hidden = YES;
                        NSString *string_msg  = result[0];
                        [SVProgressHUD dismissWithSuccess:string_msg afterDelay:1.5];
                        [[Model_user sharedInstance] loginOut];
                        double delayInSeconds = 1.5;
                        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                            if(IOS6_SIZE){
                                [self.navigationController_MI setCanDragBack:NO];
                            }
                            else{
                                [self.navigationController enabledMLBlackTransition:NO];
                            }
                            KWLLoginViewController *login = [[KWLLoginViewController alloc] initWithTag:6];
                            [self pushViewController:login];
                            //[self.navigationController popViewControllerAnimated:NO];
                            //[[NSNotificationCenter defaultCenter] postNotificationName:Notification_KWNLoginOut object:nil];
                        });
                    }break;
                    default:{
                        NSString *string_msg  = result[0];
                        [SVProgressHUD dismissWithError:string_msg afterDelay:1.5];
                    }break;
                }
            }];
        }break;
        default:
            break;
    }
}

#pragma mark - 修改密码 -
/**
 *  修改密码
 */
- (void)didClickButton_xiugai:(UIButton *)button{
    KWLFindMMViewController *controller_find = [[KWLFindMMViewController alloc] init];
    [self pushViewController:controller_find];
}

#pragma mark - 检测软件是否需要升级 -
/**
 *  检测软件是否需要升级
 */
-(void)app_checkVersion{
    NSString *newVersion;
    NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/cn/lookup?id=944922678"];
    //通过url获取数据
    NSData *data_json = [NSData dataWithContentsOfURL:url];
    NSError *error;
    NSDictionary *kindDic = [NSJSONSerialization JSONObjectWithData:data_json options:NSJSONReadingMutableLeaves error:&error];
    //从数据字典中检出版本号数据
    NSArray *configData = [kindDic valueForKey:@"results"];
    for(id config in configData){
        newVersion = [config valueForKey:@"version"];
    }
    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *msg = [NSString stringWithFormat:@"发现新版本%@，快去体验吧~ ",newVersion];
    //对比发现的新版本和本地的版本
    if ([newVersion floatValue] > [localVersion floatValue])
    {
        UIAlertView *createUserResponseAlert;
        if(IOS8_VERSION){
            createUserResponseAlert = [[UIAlertView alloc] initWithTitle:msg message:nil delegate:self cancelButtonTitle:@"我再想想" otherButtonTitles:@"立即体验", nil];
            [createUserResponseAlert show];
        }
        else{
            createUserResponseAlert = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:self cancelButtonTitle:@"我再想想" otherButtonTitles:@"立即体验", nil];
            [createUserResponseAlert show];
        }
    }
    else{
        UIAlertView *createUserResponseAlert;
        if(IOS8_VERSION){
            createUserResponseAlert = [[UIAlertView alloc] initWithTitle:@"已经是最新版啦~" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [createUserResponseAlert show];
        }
        else{
            createUserResponseAlert = [[UIAlertView alloc] initWithTitle:nil message:@"已经是最新版啦~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [createUserResponseAlert show];
        }
    }
}

#pragma mark - 响应升级提示按钮 -
/**
 *  响应升级提示按钮
 */
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    //如果选择“现在升级”
    if (buttonIndex == 1){
        //打开iTunes  方法一
        SKStoreProductViewController *storeProductViewContorller = [[SKStoreProductViewController alloc] init];
        //设置代理请求为当前控制器本身
        storeProductViewContorller.delegate = self;
        //加载一个新的视图展示
        [storeProductViewContorller loadProductWithParameters:
         //appId唯一的
         @{SKStoreProductParameterITunesItemIdentifier:@"944922678"} completionBlock:^(BOOL result, NSError *error) {
             //block回调
             if(error){
                 //NSLog(@"error %@ with userInfo %@",error,[error userInfo]);
             }else{
                 //模态弹出appstore
                 [self presentViewController:storeProductViewContorller animated:YES completion:^{
                     
                 }
                  ];
             }
         }];
    }
}

-(void)app_evaluate{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/id944922678"]];
}

//取消按钮监听
- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

@end
